package com.acme.serialization.impl;

import com.acme.serialization.ObjectSerializer;
import com.acme.serialization.SensorData;
import com.acme.serialization.SerializationException;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.*;

/**
 * @author Gregory Sobko
 */
public class JsonSensorDataObjectSerializer implements ObjectSerializer<SensorData[]> {

    private final Gson gson = new Gson();


    @Override
    public String getProtocolName() {
        return "json";

    }

    @Override
    public SensorData[] deserialize(InputStream inputStream) throws SerializationException {
        try {
            JsonReader reader = new JsonReader(new InputStreamReader(inputStream));
            return gson.fromJson(reader, SensorData[].class);
        } catch (Exception e) {
            throw new SerializationException(e);
        }

    }

    @Override
    public void serialize(SensorData[] object, OutputStream outputStream) throws SerializationException {
        try {
            JsonWriter jsonWriter = new JsonWriter(new OutputStreamWriter(outputStream));
            gson.toJson(object, SensorData[].class, jsonWriter);
            jsonWriter.flush();
        } catch (IOException e) {
            throw new SerializationException(e);
        }
    }
}
